﻿using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using System;
using Umi.Crypto.Abstraction.Ciphers;
using KeyParameter = Umi.Crypto.Abstraction.Keys.KeyParameter;

namespace Umi.Web.Crypto.Crypto.Aes
{

    public class AesCryptoService : ICryptoService
    {
        private readonly IBufferedCipher _cipher;

        public AesCryptoService(string name)
        {
            if (name.IndexOf("aes", StringComparison.OrdinalIgnoreCase) < 0)
                throw new ArgumentException("not suppend");
            _cipher = CipherUtilities.GetCipher(name);
        }

        public string Name => _cipher.AlgorithmName;

        public byte[] Crypto(byte[] data, KeyParameter key)
        {
            ICipherParameters parameters = null;
            if (key is AesKeyParameter aesKey)
            {
                parameters = new Org.BouncyCastle.Crypto.Parameters.KeyParameter(aesKey.Key);
                if (aesKey.IV != null)
                    parameters = new ParametersWithIV(parameters, aesKey.IV);
            }
            _cipher.Init(true, parameters);
            return _cipher.DoFinal(data); ;
        }

        public byte[] Decrypto(byte[] data, KeyParameter key)
        {
            ICipherParameters parameters = null;
            if (key is AesKeyParameter aesKey)
            {
                parameters = new Org.BouncyCastle.Crypto.Parameters.KeyParameter(aesKey.Key);
                if (aesKey.IV != null)
                    parameters = new ParametersWithIV(parameters, aesKey.IV);
            }
            _cipher.Init(false, parameters);
            return _cipher.DoFinal(data); ;
        }

    }
}
